import React from 'react';
import './scheduleManage.less';
import {browserHistory} from 'react-router';
import { Tabs ,Table,Button, Modal,Icon,Select} from 'antd';
import $ from 'jquery';
import config from '../../config/config';
const allRouter=config.router;
const TabPane = Tabs.TabPane;
const Option = Select.Option;
const token = sessionStorage.getItem('token');

//副类
class AssistantTherapyTemplateTable extends React.Component{
    constructor(props){
        super(props);
        this.state={
            currentdate:'',//中间显示的一周的日期区间
            dateStart:'',//用于传递时间区间起始
            dateEnd:'',//用于传递时间区间结尾
            month:[],//月份，用于表头显示
            strDate:[],//日期，用于表头显用
            clickCount:0,//记录上一周或下一周点击次数
            nowDate:new Date(),//获得现在日期函数
            allDateEveryWeek:[],//一周总的时间，用于返回数据的时间比对
            pagesize: 10,// 每页显示的页数
            pageindex: 1,// 当前页
            schedulingsList:[],//班次列表
            allScheduleList:[],//所有排班列表
            testData:[],//用于数据的显示
            dedicateList:[],//角色已失效列表
            isDisabledSchdule:false,//表示总复制上周是否禁用
            allScheduleLists:[],//所有角色名字列表
        }
    }
    componentWillMount() {
        this.getScheduleList();
    }
    componentDidMount() {
        this.iniDate(this.state.nowDate);
    }
    //日期函数
    iniDate(now){
        //获取指定的日期和时间距 1970 年 1 月 1 日午夜（GMT 时间）之间的毫秒数。
        let nowTime = now.getTime() ;
        //获取星期及几
        let day = now.getDay();
        //一天的毫秒数
        let oneDayLong = 24*60*60*1000 ;
        console.log(day);
        let MondayTime;
        let SundayTime;
        if(day==0){
            //获取本周所在周一
             MondayTime = nowTime - (day-1+7)*oneDayLong ;
            //获取本周所在周末
             SundayTime = nowTime + (7-day-7)*oneDayLong ;
        }else{
            //获取本周所在周一
             MondayTime = nowTime - (day-1)*oneDayLong ;
            //获取本周所在周末
             SundayTime = nowTime + (7-day)*oneDayLong ;
        }
        //转化日期  星期一的日期和星期天的日期
        let allDateEveryWeek=[];
        let monday = new Date(MondayTime);
        let sunday = new Date(SundayTime);
        //星期一的月份
        let month = monday.getMonth() + 1;
        //星期一的日期
        let strDate = monday.getDate();
        //星期天的月份
        let month1 = sunday.getMonth() + 1;
        //星期天的日期
        let strDate1 = sunday.getDate();
        let currentdate = monday.getFullYear() + "年" + month + "月" + strDate +"日"+ "-" + sunday.getFullYear() + "年" + month1 + "月" + strDate1+"日";
        // let dateStart= (monday.getFullYear()+'-'+(month<10?'0':'')+month+'-'+(strDate<10?'0':'')+strDate);
        // let dateEnd= (sunday.getFullYear()+'-'+(month1<10?'0':'')+month1+'-'+(strDate1<10?'0':'')+strDate1);
        let dateStart= monday.toLocaleDateString();
        let dateEnd= sunday.toLocaleDateString();
        let monthTotalItem=this.state.month;
        let strDateItem=this.state.strDate;
        for(let i=0;i<7;i++){
            allDateEveryWeek.push(new Date(MondayTime+(i*oneDayLong)).toLocaleDateString());
            monthTotalItem.push(new Date(MondayTime+(i)*oneDayLong).getMonth() + 1);
            strDateItem.push(new Date(MondayTime+(i)*oneDayLong).getDate());
        }
        // console.log(currentdate);
        // console.log(monthTotalItem);
        // console.log(strDateItem);
        this.setState({
            allDateEveryWeek,
            currentdate,
            month:monthTotalItem,
            strDate:strDateItem,
            dateStart:dateStart,
            dateEnd:dateEnd,
        },()=>{
            // console.log(this.state.allDateEveryWeek);
            // console.log(this.state.currentdate);
            // console.log(this.state.dateStart);
            // console.log(this.state.dateEnd);
            // console.log(this.state.month);
            this.getDoctorScheduleList(this.state.dateStart,this.state.dateEnd);
        })
    }

    //获取总的医生排班列表
    getDoctorScheduleList(time1,time2){
        let url=allRouter.patientOrigin+'/doctor/listscheduling ';
        $.ajax({
            url:url,
            type: "POST",
            async: true,
            headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
            data:{
                starttime:time1,
                endtime:time2
            },
            success:data1=>{
                console.log("医生排班列表:");
                console.log(data1);
                if(data1.code===200){
                    this.setState({
                        allScheduleList:data1.data,
                    },()=>{
                        let testData=[];
                        console.log('this.props.parentData');
                        console.log(this.props.parentData);
                        // testData.push({name:'不坐班',_id:'',department:'',role:'',});
                        this.props.parentData.map(item=>{
                            if(data1.data.length){
                                let count=0;
                                data1.data.map(item1=>{
                                    if(item._id===item1.id){
                                        if(item1.arrangemes.length){
                                            item1.arrangemes=item1.arrangemes.filter(k=>{if(k.arrangetime){return k;}});
                                        }
                                        let obj={name:item.name,_id:item._id,department:item.department,role:item.role,days:item1.arrangemes,selectedDepartment:item1.department}
                                        this.state.allDateEveryWeek.map((dayItem,i)=>{
                                            item1.arrangemes.map(item2=>{
                                                if(new Date(item2.arrangetime).getTime()===(new Date(dayItem).getTime())){
                                                    obj['day'+i]=item2.arrangename;
                                                }
                                            })
                                        });
                                        testData.push(obj);
                                    }else{
                                        count++;
                                        if(count===data1.data.length){
                                            testData.push({name:item.name,_id:item._id,department:item.department,role:item.role,});
                                        }
                                    }
                                })
                            }else{
                                testData.push({name:item.name,_id:item._id,department:item.department});
                            }

                        });
                        this.setState({
                            testData,
                        },()=>{
                            console.log('this.state.testData');
                            console.log(this.state.testData);
                            this.state.testData.map(record=>{
                                if(this.state.dedicateList.indexOf(record.day1)!==-1||this.state.dedicateList.indexOf(record.day2)!==-1||this.state.dedicateList.indexOf(record.day3)!==-1||this.state.dedicateList.indexOf(record.day4)!==-1||this.state.dedicateList.indexOf(record.day5)!==-1||this.state.dedicateList.indexOf(record.day6)!==-1
                                ){
                                    this.setState({
                                        isDisabledSchdule:true
                                    })
                                }
                            });
                        })
                    })
                }else{
                    console.log("获取医生排班列表出错");
                }
            },
            error:err=>{
                console.log(err);
            }
        })
    }

    //获取班次列表
    getScheduleList() {
        let url=allRouter.patientOrigin+'/sheduling/list';
        console.log(url);
        $.ajax({
            url:url,
            type:'GET',
            async: true,
            headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
            success:data=>{
                console.log(data);
                if(data.code===200){
                    //dedicateList被禁用的班次列表,
                    //allScheduleLists  所有班次列表
                    let dedicateList=[];
                    let allScheduleLists=[];
                    if (data.schedulings.length > 0) {
                        data.schedulings.forEach((ele, i) => {
                            if(ele.state==='禁用'){
                                dedicateList.push(ele.name);
                            }
                            allScheduleLists.push(ele.name);
                        });
                    }
                    allScheduleLists.push('不坐班');
                    console.log(dedicateList);
                    data.schedulings.unshift({
                        name:"不坐班",
                        state: "启用",
                        _id:'11111'
                    });
                    this.setState({
                        schedulingsList:data.schedulings,
                        dedicateList,
                        allScheduleLists,
                    },()=>{
                        console.log('schedulingsList');
                        console.log(this.state.schedulingsList);
                    })
                }else{
                    console.log("获取班次列表出错");
                }
            },
            error:err=>{ console.log(err);},
        });
    }
    //选择科室变化函数
    handleDepartmentChange(DoctorId,name,role,dpartmentId,){
        // //哪个医生的id
        // console.log(+DoctorId);
        // //医生姓名
        // console.log(name);
        // //选择的科室的id
        // console.log(dpartmentId);
        let url=allRouter.patientOrigin+'/doctor/updatedepartment';
        $.ajax({
            url:url,
            type: "post",
            async: true,
            headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
            data:{
                id:DoctorId,
                department:dpartmentId,
                doctorname:name,
                role,
            },
            success:data=>{
                console.log(data);
                if(data.code===200){
                    console.log(data.mes);
                    this.getDoctorScheduleList(this.state.dateStart,this.state.dateEnd);
                    const modal = Modal.success({
                        title: '选择科室',
                        content: '选择科室成功',
                    });
                    setTimeout(() => modal.destroy(), 2000);
                    // this.setState({
                    //     selectedDepartment:dpartmentId,
                    // })
                }else{
                    console.log(data.mes);
                }
            },
            error:err=>{
                console.log(err);
            }
        })
    }
    //选择班次触发函数
    handleChange(DoctorId,name,No,role,scheduleId,){
        // //医生Id
        // console.log(DoctorId);
        // //医生名称
        // console.log(name);
        // //一周的第几天，计算日期
        // console.log(No);
        // //班次Id
        // console.log(scheduleId);
        const{month,strDate}=this.state;
        let myDate='';
        myDate+=new Date().getFullYear()+'/';
        // myDate+=month[No]<10?'0':'';
        myDate+=month[No]+'/';
        // myDate+=strDate[No]<10?'0':'';
        myDate+=strDate[No];
        console.log(myDate);
        let url=allRouter.patientOrigin+'/doctor/updateclasses';
        $.ajax({
            url:url,
            type: "post",
            async: true,
            headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
            data:{
                id:DoctorId,
                name:scheduleId,
                time:myDate,
                doctorname:name,
                role,
            },
            success:data=>{
                console.log(data);
                if(data.code===200){
                    //console.log(data.mes);
                    this.getDoctorScheduleList(this.state.dateStart,this.state.dateEnd);
                    const modal = Modal.success({
                        title: '选择班次',
                        content: '选择班次成功',
                    });
                    setTimeout(() => modal.destroy(),2000);
                }else{
                    console.log(data.mes);
                }
            },
            error:err=>{
                console.log(err);
            }
        })
    }
    //上一周点击事件
    lastWeekBtn(){
        let clickCount=this.state.clickCount;
        clickCount--;
        this.setState({
            clickCount,
            month:[],
            strDate:[]
        },()=>{
            let date = new Date(new Date().getTime() + clickCount*7*24*3600*1000);
            this.iniDate(date);
        });

    }
    //下一周点击事件
    nextWeekBtn(){
        let clickCount=this.state.clickCount;
        clickCount++;
        this.setState({
            clickCount,
            month:[],
            strDate:[]
        },()=>{
            let date = new Date(new Date().getTime() + clickCount*7*24*3600*1000);
            this.iniDate(date);
        });

    }
    //回到本周点击事件
    thisWeekBtn(){
        this.setState({
            month:[],
            strDate:[],
            clickCount:0
        },()=>{
            let date = new Date(new Date().getTime());
            this.iniDate(date);
        });

    }
    //单个医生复制上周点击事件
    handleCopySingleDoctor(record){
        let url=allRouter.patientOrigin+'/doctor/copyscheduling';
        $.ajax({
            url:url,
            type: "GET",
            async: true,
            headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
            data:{
                id:record._id,
                time:this.state.dateStart
            },
            success:data=>{
                console.log('diajgsaefgjkosehijoh');
                console.log(data);
                this.getDoctorScheduleList(this.state.dateStart,this.state.dateEnd);

            },
            error:err=>{
                console.log(err);
            }
        })
    }
    //复制上周点击事件
    handleCopyAll(){
        let arr=[];
        this.state.testData.map(item=>{
            arr.push(item._id);
        });
        console.log(arr);
        let url=allRouter.patientOrigin+'/doctor/copyall';
        $.ajax({
            url:url,
            type: "POST",
            async: true,
            headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
            data:{
                id:JSON.stringify(arr),
                time:this.state.dateStart
            },
            success:data=>{
                console.log(data);
                this.getDoctorScheduleList(this.state.dateStart,this.state.dateEnd);
            },
            error:err=>{
                console.log(err);
            }
        })
    }
    //显示提示消息
    showTips(){
        const modal = Modal.error({
            title: '操作失败',
            content: '操作失败！信息有变动，请手动操作',
        });
        setTimeout(() => modal.destroy(),2000);
    }
    render(){
        const{currentdate,month,strDate}=this.state;
        const columns = [
            {
                title: '医生',
                dataIndex:'name',
                width: 130,
            }, {
                title: '科室',
                dataIndex:'department',
                width: 120,
                render:(text,record)=> <Select  placeholder="请选择科室" onChange={this.handleDepartmentChange.bind(this,record._id,record.name,record.role)} style={{ width: '100%' }} value={record.selectedDepartment}>
                    {text.length?text.map(item=>{
                        if(item){
                            return <Option value={item._id} key={item._id}>{item.name}</Option>
                        }
                    }):''}
                </Select>
            },{
                title: '周一 '+month[0]+"月"+strDate[0]+'日',
                width: 120,
                dataIndex:'day0',
                render:(text,record)=> <Select  placeholder="请选择班次" style={{ width: '100%' ,color:(this.state.dedicateList.indexOf(text)===-1)?(!text?'#bbb':(text==="不坐班"?'#bbb':'')):'red'}} onChange={this.handleChange.bind(this,record._id,record.name,0,record.role)} value={text?(this.state.dedicateList.indexOf(text)===-1?text:'(已失效)'+text):'不坐班'}>
                    {this.state.schedulingsList?this.state.schedulingsList.map(
                        item => {
                            return <Option key={item._id} value={item.name} disabled={this.state.dedicateList.indexOf(item.name)!==-1}>{this.state.dedicateList.indexOf(item.name)===-1?item.name:'(已失效)'+item.name}</Option>}
                    ):''}
                </Select>
            },{
                title: '周二 '+month[1]+"月"+strDate[1]+'日',
                width: 120,
                dataIndex:'day1',
                render:(text,record)=> <Select   placeholder="请选择班次" style={{ width: '100%' ,color:this.state.dedicateList.indexOf(text)===-1?(!text?'#bbb':(text==="不坐班"?'#bbb':'')):'red'}} onChange={this.handleChange.bind(this,record._id,record.name,1,record.role)} value={text?(this.state.dedicateList.indexOf(text)===-1?text:'(已失效)'+text):'不坐班'}>
                    {this.state.schedulingsList?this.state.schedulingsList.map(
                        item => {
                            return <Option key={item._id} value={item.name} disabled={this.state.dedicateList.indexOf(item.name)!==-1}>{this.state.dedicateList.indexOf(item.name)===-1?item.name:'(已失效)'+item.name}</Option>}
                    ):''}
                </Select>
            },{
                title:'周三 '+month[2]+"月"+strDate[2]+'日',
                width: 120,
                dataIndex:'day2',
                render:(text,record)=> <Select   placeholder="请选择班次" style={{ width: '100%' ,color:this.state.dedicateList.indexOf(text)===-1?(!text?'#bbb':(text==="不坐班"?'#bbb':'')):'red'}} onChange={this.handleChange.bind(this,record._id,record.name,2,record.role)} value={text?(this.state.dedicateList.indexOf(text)===-1?text:'(已失效)'+text):'不坐班'}>
                    {this.state.schedulingsList?this.state.schedulingsList.map(
                        item => {
                            return <Option key={item._id} value={item.name} disabled={this.state.dedicateList.indexOf(item.name)!==-1}>{this.state.dedicateList.indexOf(item.name)===-1?item.name:'(已失效)'+item.name}</Option>}
                    ):''}
                </Select>
            },{
                title: '周四'+month[3]+"月"+strDate[3]+'日',
                width: 120,
                dataIndex:'day3',
                render:(text,record)=> <Select   placeholder="请选择班次"style={{ width: '100%' ,color:this.state.dedicateList.indexOf(text)===-1?(!text?'#bbb':(text==="不坐班"?'#bbb':'')):'red'}} onChange={this.handleChange.bind(this,record._id,record.name,3,record.role)} value={text?(this.state.dedicateList.indexOf(text)===-1?text:'(已失效)'+text):'不坐班'}>
                    {this.state.schedulingsList?this.state.schedulingsList.map(
                        item => {
                            return <Option key={item._id} value={item.name} disabled={this.state.dedicateList.indexOf(item.name)!==-1}>{this.state.dedicateList.indexOf(item.name)===-1?item.name:'(已失效)'+item.name}</Option>}
                    ):''}
                </Select>
            },{
                title: '周五 '+month[4]+"月"+strDate[4]+'日',
                width: 120,
                dataIndex:'day4',
                render:(text,record)=> <Select   placeholder="请选择班次" style={{ width: '100%' ,color:this.state.dedicateList.indexOf(text)===-1?(!text?'#bbb':(text==="不坐班"?'#bbb':'')):'red'}} onChange={this.handleChange.bind(this,record._id,record.name,4,record.role)} value={text?(this.state.dedicateList.indexOf(text)===-1?text:'(已失效)'+text):'不坐班'}>
                    {this.state.schedulingsList?this.state.schedulingsList.map(
                        item => {
                            return <Option key={item._id} value={item.name} disabled={this.state.dedicateList.indexOf(item.name)!==-1}>{this.state.dedicateList.indexOf(item.name)===-1?item.name:'(已失效)'+item.name}</Option>}
                    ):''}
                </Select>
            },{
                title:'周六 '+month[5]+"月"+strDate[5]+'日',
                width: 120,
                dataIndex:'day5',
                render:(text,record)=> <Select   placeholder="请选择班次" style={{ width: '100%' ,color:this.state.dedicateList.indexOf(text)===-1?(!text?'#bbb':(text==="不坐班"?'#bbb':'')):'red'}} onChange={this.handleChange.bind(this,record._id,record.name,5,record.role)} value={text?(this.state.dedicateList.indexOf(text)===-1?text:'(已失效)'+text):'不坐班'}>
                    {this.state.schedulingsList?this.state.schedulingsList.map(
                        item => {
                            return <Option key={item._id} value={item.name}disabled={this.state.dedicateList.indexOf(item.name)!==-1}>{this.state.dedicateList.indexOf(item.name)===-1?item.name:'(已失效)'+item.name}</Option>}
                    ):''}
                </Select>
            },{
                title:'周天 '+month[6]+"月"+strDate[6]+'日',
                width: 120,
                dataIndex:'day6',
                render:(text,record)=> <Select  placeholder="请选择班次" style={{ width: '100%' ,color:this.state.dedicateList.indexOf(text)===-1?(!text?'#bbb':(text==="不坐班"?'#bbb':'')):'red'}} onChange={this.handleChange.bind(this,record._id,record.name,6,record.role)} value={text?(this.state.dedicateList.indexOf(text)===-1?text:'(已失效)'+text):'不坐班'}>
                    {this.state.schedulingsList?this.state.schedulingsList.map(
                        item => {
                            return <Option key={item._id} value={item.name} disabled={this.state.dedicateList.indexOf(item.name)!==-1}>{this.state.dedicateList.indexOf(item.name)===-1?item.name:'(已失效)'+item.name}</Option>}
                    ):''}
                </Select>
            }, {
                title: '操作',
                width: 200,
                render: (text, record) => (
                    <div>
                        <Button type="primary"
                                onClick={(this.state.dedicateList.indexOf(record.day1)!==-1||
                                    this.state.dedicateList.indexOf(record.day2)!==-1||this.state.dedicateList.indexOf(record.day3)!==-1||
                                    this.state.dedicateList.indexOf(record.day4)!==-1||this.state.dedicateList.indexOf(record.day5)!==-1||
                                    this.state.dedicateList.indexOf(record.day6)!==-1)?this.showTips.bind(this):this.handleCopySingleDoctor.bind(this,record)}>复制上周</Button>
                    </div>
                )
            }
        ];
        return(
            <div>
                {/*增加按钮*/}
                    <div className="my-clear-fix"  style={{marginBottom:'20px'}}>
                        <Button  onClick={this.lastWeekBtn.bind(this)}><Icon type="left" />上一周</Button>
                        <Button　onClick={this.nextWeekBtn.bind(this)}>下一周<Icon type="right" /></Button>
                        <Button type="primary" style={{marginLeft:'20px'}} onClick={this.thisWeekBtn.bind(this)}>回到本周</Button>
                        <p style={{textAlign:'center',fontWeight:'bold',fontSize:'16px',display:'inline-block',marginLeft:'25%'}}>{currentdate}</p>
                        <Button style={{float:'right'}} onClick={this.state.isDisabledSchdule?this.showTips.bind(this):this.handleCopyAll.bind(this)} >复制上周</Button>
                    </div>
                <div className='all-roles-table'>
                    <Table
                        rowKey="_id"
                        columns={columns}
                        dataSource={this.state.testData}
                        pagination={false}
                        bordered
                    />
                </div>
            </div>
        )
    }
}

//主类
class ScheduleManage extends React.Component {
    constructor(props){
        super(props);
        this.state={
            doctorList:[],//医生列表
            PharmacyList:[],//药房列表
            allScheduleList:[],//所有排班信息列表
            activeKey:1,
            isHavingData:false,//标志是否请求完成
        }
    }
    componentWillMount() {
        this.getDoctorList();
    }
    componentDidMount() {
    }
    //获取医生列表
    getDoctorList(){
        let url=allRouter.patientOrigin+'/doctor/list';
        $.ajax({
            url:url,
            type: "get",
            async: true,
            headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
            success:data=>{
                console.log(data);
                if(data.code===200){
                    this.setState({
                        doctorList:data.users.filter(key=>key.department.filter(key=>key!=null).length>0&&key.role==='医生'&&key.state!=='禁用'),
                        PharmacyList:data.users.filter(key=>key.role==='药房'&&key.state!=='禁用'),
                        isHavingData:true,
                    },()=>{
                        console.log('doctorList');
                        console.log(this.state.doctorList);
                        console.log('PharmacyList');
                        console.log(this.state.PharmacyList);
                    })
                }else{
                    console.log("获取员工列表出错");
                }
            },
            error:err=>{
                console.log(err);
            }
        })
    }

    handleTabChange(activeKey){
        console.log(activeKey);
        this.setState({
            activeKey
        })
    }

    render(){
        return (
            <div className="container">
                <div className="assistant-therapy-box">
                    <Tabs defaultActiveKey="1"  onChange={this.handleTabChange.bind(this)} >
                        {this.state.isHavingData?<TabPane tab="医生排班" key="1"><AssistantTherapyTemplateTable  activeKey={this.state.activeKey} parentData={this.state.doctorList} isDotor={true}></AssistantTherapyTemplateTable></TabPane>:''}
                    </Tabs>
                </div>
            </div>
        );
    }
}
export default ScheduleManage;